﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;

namespace RoadTeam.Pase
{
  public  class BasePase
    {
        protected static  List<T> DtToList<T>(DataTable dt)
        {
            List<T> li = new List<T>();
            T entity = default(T);
            String TempName = String.Empty;
            foreach (DataRow dr in dt.Rows)
            {
                entity = Activator.CreateInstance<T>();
                PropertyInfo[] PropertInfos = entity.GetType().GetProperties();
                foreach (PropertyInfo p in PropertInfos)
                {
                    TempName = p.Name;
                    if (!dt.Columns.Contains(TempName)) continue;
                    if (!p.CanWrite) continue;

                    object obj = dr[TempName];
                    if (obj == null || obj == DBNull.Value) continue;

                    if (obj == typeof(string))
                    {
                        string Temp = obj.ToString();
                        p.SetValue(entity, Temp, null);
                    }
                    else if (obj == typeof(Int32))
                    {
                        Int32 Temp = Convert.ToInt32(obj);
                        p.SetValue(entity, Temp, null);
                    }

                    else if (obj == typeof(long))
                    {
                        long Temp = long.Parse(obj.ToString());
                        p.SetValue(entity, Temp, null);
                    }
                    else
                    {
                        object Temp = Convert.ChangeType(obj, p.PropertyType);
                        p.SetValue(entity, Temp, null);
                    }
                }
                li.Add(entity);
            }
            return li;
        }
    }
}
